/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.siteEncheres.client.seance;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Image;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.DateFieldDef;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.FloatFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;

import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListener;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.gwtext.client.widgets.layout.VerticalLayout;
import domain.Observer.Seance;
import domain.Utilisateur;
import java.util.ArrayList;
import java.util.List;
import org.siteEncheres.client.DoubleBox;

/**
 *
 * @author Damador
 */
public class GrilleSeance extends Panel {
    
    private List<Seance> listeSeances = new ArrayList<Seance>();
    private Utilisateur utilisateurEnCours = new Utilisateur();
    private Seance seanceEncours = null;
    private Panel panelGeneral = new Panel();
    private Panel panelGrille = new Panel();
    private Panel panelDetail = new Panel();
    private Label lblTitre = new Label();
    private Label lblDescription = new Label();
    private Label lblCategorie = new Label();
    private Label lblPrix = new Label();
    private Label lblPrixReserve = new Label();
    private Label lblDateOuverture = new Label();
    private Label lblDateFermeture = new Label();
    private Label lblVendeur = new Label();
    private Image photo = new Image("images/iphone-4.jpg");
    private Button btnRejoindreSeance = new Button("Rejoindre la seance");
    private Button btnEncherir = new Button("Encherir");
    private Button btnQuitterSeance = new Button("Quitter la seance");
    private DoubleBox txtMontant = new DoubleBox();
    private Double prixEncheri;
    
    final AsyncCallback<Boolean> callbackParticipeSeance = new AsyncCallback<Boolean>() {

        @Override
        public void onSuccess(Boolean result) {
            if(result){
                setVisibleBouton(true);
            }else{
                setVisibleBouton(false);
            }
        }

        @Override
        public void onFailure(Throwable caught) {
            String exception = formaterException(caught.getMessage());
            MessageBox.alert(exception);
        }
    };
    
    final AsyncCallback callbackEncherir = new AsyncCallback() {

        @Override
        public void onSuccess(Object result) {
            lblPrix.setText(prixEncheri.toString());
        }
        

        
        @Override
        public void onFailure(Throwable caught) {
            String exception = formaterException(caught.getMessage());
            MessageBox.alert(exception);
        }
    };
    
    final AsyncCallback callbackQuitterSeance = new AsyncCallback() {

        @Override
        public void onSuccess(Object result) {
            setVisibleBouton(false);
        }

        @Override
        public void onFailure(Throwable caught) {
            String exception = formaterException(caught.getMessage());
            MessageBox.alert(exception);
        }
    };
    
    final AsyncCallback callbackRejoindreSeance = new AsyncCallback() {

        @Override
        public void onSuccess(Object result) {
            setVisibleBouton(true);
            
        }

        @Override
        public void onFailure(Throwable caught) {
            String exception = formaterException(caught.getMessage());
            MessageBox.alert(exception);
        }
    };
    
    public GrilleSeance(List<Seance> listeSeance, final Utilisateur utilisateurEnCours) {
        this.listeSeances = listeSeance;
        this.utilisateurEnCours = utilisateurEnCours;
       
        
        
        panelGeneral.setLayout(new HorizontalLayout(5));
        
        panelGrille.setBorder(true);
        
        panelDetail.setBorder(true);
        panelDetail.setTitle("Détail de la séance");
        panelDetail.setLayout(new VerticalLayout(5));
        panelDetail.setSize(550, 500);
        
        Panel panelTitre = new Panel();
        panelTitre.setLayout(new HorizontalLayout(5));
        panelTitre.add(new Label("Titre: "));
        panelTitre.add(lblTitre);
        panelDetail.add(panelTitre);
        
        Panel panelDescription = new Panel();
        panelDescription.setLayout(new HorizontalLayout(5));
        panelDescription.add(new Label("Description: "));
        panelDescription.add(lblDescription);
        panelDetail.add(panelDescription);
        
        
        Panel panelCategorie = new Panel();
        panelCategorie.setLayout(new HorizontalLayout(5));
        panelCategorie.add(new Label("Catégorie: "));
        panelCategorie.add(lblCategorie);
        panelDetail.add(panelCategorie);
        
        
        Panel panelPrix = new Panel();
        panelPrix.setLayout(new HorizontalLayout(5));
        panelPrix.add(new Label("Prix: "));
        panelPrix.add(lblPrix);
        panelDetail.add(panelPrix);
        
        Panel panelPrixReserve = new Panel();
        panelPrixReserve.setLayout(new HorizontalLayout(5));
        panelPrixReserve.add(new Label("Prix de réserve: "));
        panelPrixReserve.add(lblPrixReserve);
        panelDetail.add(panelPrixReserve);
        
        Panel panelDateOuverture = new Panel();
        panelDateOuverture.setLayout(new HorizontalLayout(5));
        panelDateOuverture.add(new Label("Date d'ouverture: "));
        panelDateOuverture.add(lblDateOuverture);
        panelDetail.add(panelDateOuverture);
        
        Panel panelDateFermeture = new Panel();
        panelDateFermeture.setLayout(new HorizontalLayout(5));
        panelDateFermeture.add(new Label("Date de fermeture: "));
        panelDateFermeture.add(lblDateFermeture);
        panelDetail.add(panelDateFermeture);
        
        Panel panelVendeur = new Panel();
        panelVendeur.setLayout(new HorizontalLayout(5));
        panelVendeur.add(new Label("Vendeur: "));
        panelVendeur.add(lblVendeur);
        panelDetail.add(panelVendeur);
        
        Panel panelPhoto = new Panel();
        //panelVendeur.setLayout(new HorizontalLayout(5));
        //panelVendeur.add(new Label("Vendeur: "));
        panelPhoto.add(photo);
        photo.setSize("100px", "100px");
        panelDetail.add(panelPhoto);
        
        Panel panelBouton = new Panel();
        panelBouton.setLayout(new HorizontalLayout(5));
        panelBouton.add(btnRejoindreSeance);
        panelBouton.add(btnEncherir);
        txtMontant.setWidth("60px");
        panelBouton.add(txtMontant);
        panelBouton.add(btnQuitterSeance);
       
        btnEncherir.setVisible(false);
        btnQuitterSeance.setVisible(false);
        btnRejoindreSeance.setVisible(false);
        txtMontant.setVisible(false);
        panelDetail.add(panelBouton);
        
        /////////////////// Grille ////////////////////////////////////////////
        RecordDef recordDef = new RecordDef(
                new FieldDef[]{
                    new StringFieldDef("titre"),  
                    new FloatFieldDef("prix"),  
                    new DateFieldDef("date")
                });
        
        final GridPanel grid = new GridPanel();  
  
        Object[][] data = getSeanceData(listeSeance);  
        MemoryProxy proxy = new MemoryProxy(data);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        Store store = new Store(proxy, reader);  
        store.load();  
        grid.setStore(store);  
  
        ColumnConfig[] columns = new ColumnConfig[]{
            new ColumnConfig("Titre", "titre", 190, true, null, "titre"),  
                new ColumnConfig("Prix de l'enchere", "prix", 100),  
                new ColumnConfig("Date de fin", "date", 220)};

        ColumnModel columnModel = new ColumnModel(columns);  
        grid.setColumnModel(columnModel);  
  
        grid.setFrame(true);  
        grid.setStripeRows(true);  
        grid.setAutoExpandColumn("titre");  
  
        grid.setHeight(350);  
        grid.setWidth(400);  
        grid.setTitle("Liste des seances");
        //////////////////////////////////////////////////////////////////////

        panelGrille.add(grid);  
        
        grid.addGridRowListener(new GridRowListener() {

            @Override
            public void onRowClick(GridPanel grid, int rowIndex, com.gwtext.client.core.EventObject e) {
                //Window.alert(listeSeances.get(rowIndex).toString());
                Seance seance = listeSeances.get(rowIndex);
                seanceEncours = seance;
                Integer ids = seanceEncours.getId_seance();
                Integer id = utilisateurEnCours.getIdUtilisateur();
                //Window.alert("id seance" + ids.toString() + ", iduser" + id);
                
                lblTitre.setText(seance.getProduit().getTitre());
                lblDescription.setText(seance.getProduit().getDescription());
                lblCategorie.setText(seance.getProduit().getCategorie().getNom());
                Double prixDepart = seance.getPrix_depart();
                lblPrix.setText(prixDepart.toString());
                Double prixReserve = seance.getReserve();
                lblPrixReserve.setText(prixReserve.toString());
                lblDateOuverture.setText(seance.getDate_ouverture().toString());
                lblDateFermeture.setText(seance.getDate_fermeture().toString());
                
                getService().participeASeance(seance.getId_seance(), utilisateurEnCours.getIdUtilisateur(), callbackParticipeSeance);        
            }

            @Override
            public void onRowDblClick(GridPanel grid, int rowIndex, com.gwtext.client.core.EventObject e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void onRowContextMenu(GridPanel grid, int rowIndex, com.gwtext.client.core.EventObject e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        
        
        
        btnEncherir.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                if(txtMontant.getText().compareTo("") != 0){
                    Double montant = Double.parseDouble(txtMontant.getText());
                    prixEncheri = montant;
                    getService().encherir(seanceEncours.getId_seance(), utilisateurEnCours.getIdUtilisateur()
                       , montant, callbackQuitterSeance);
                }
            }
        });
        
        btnQuitterSeance.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
               getService().quitterSeance(seanceEncours.getId_seance(), utilisateurEnCours.getIdUtilisateur()
                       , callbackQuitterSeance);
            }
        });
        
        btnRejoindreSeance.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
               getService().rejoindeSeance(seanceEncours.getId_seance(), utilisateurEnCours.getIdUtilisateur()
                       , callbackRejoindreSeance);
            }
        });
        
        panelGeneral.add(panelGrille);
        panelGeneral.add(panelDetail);
        add(panelGeneral);
    }

    private Object[][] getSeanceData(List<Seance> listeSeance) {
        Object[][] tableauSeance = new Object[listeSeance.size()][3];
        for (int i = 0; i < listeSeance.size(); i++) {
        tableauSeance[i] = new Object[]{listeSeance.get(i).getProduit().getTitre(),
            listeSeance.get(i).getPrix_depart(),
            listeSeance.get(i).getDate_fermeture()};
        }
        return tableauSeance;
    }
    
    public static GwtSeanceAsync getService() {
        return GWT.create(GwtSeance.class);
    }
    
    /**
     * M√©thode servant a separer le "java.lang.Exception:" du
     * message de l'exception qu on ne veut pas a l affichage.
     * 
     * @param exception Message contenu dans l exception.
     * @return ce qu il y a apres le "java.lang.Exception"
     * si cette chaine est presente, le message en entier sinon.
     */
    public String formaterException(String exception) {
        String[] split = exception.split(":");
        if (split[0].compareTo("java.lang.Exception") == 0) {
            return split[1];
        } else {
            return exception;
        }
    }
    
    /**
     * 
     * @param visible met les boutons Encherir, QuitterSeance et la txtBox de
     * montant à visible et rejoindre seance à l'inverse.
     */
    public void setVisibleBouton(Boolean visible){
        btnEncherir.setVisible(visible);
        btnQuitterSeance.setVisible(visible);
        txtMontant.setVisible(visible);
        btnRejoindreSeance.setVisible(!visible);
        
    }
}
